/**
 * 
 */
package export;

import java.io.BufferedWriter;
import java.io.FileWriter;

import optimization.naturalOptimization.population.Population;
import optimization.naturalOptimization.population.individual.Individual;
import optimization.naturalOptimization.population.individual.pso.Particle;

/**
 * This class provides methods to export individual data.
 * 
 * @author Kevin Wagner
 * @version 1.0
 */
public class IndividualDataExport {

	private static String sep = System.getProperty("line.separator");

	/**
	 * Export the data of the population
	 * 
	 * @param swarm
	 * @param gen
	 *            current generation
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void exportSwarmData(Population swarm, int gen)
			throws Exception {
		// Create file
		FileWriter fstream = new FileWriter("swarm.txt", true);
		BufferedWriter out = new BufferedWriter(fstream);
		out.write("-------------------------------------------------------"
				+ sep);
		out.write("Generation " + gen + sep);
		for (int i = 0; i < swarm.getNumberOfIndividuals(); i++) {
			Particle particle = (Particle) swarm.getIndividual(i);
			out.write("Particle " + i + sep);
			out.write("Position:" + sep);
			out.write(swarm.getParentOptimization().getSearchSpace()
					.toString(particle.getPosition())+sep);
			out.write("Position Fitness: "+particle.getPositionFitness() + sep);
			out.write("Personal Best:" + sep);
			out.write(swarm.getParentOptimization().getSearchSpace()
					.toString(particle.getPersonalBest())+sep);
			out.write("Personal Best Fitness: "+particle.getPersonalBestFitness() + sep);
			out.write("Neighborhood Best:" + sep);
			out.write(swarm.getParentOptimization().getSearchSpace()
					.toString(particle.getNeighborhoodBest())+sep);
			out.write("Neighborhood Best Fitness: "+particle.getNeighborhoodBestFitness() + sep);
		}
		out.flush();
		// Close the output stream
		out.close();
	}
	
	/**
	 * Export the data of the population
	 * 
	 * @param pop
	 * @param gen
	 *            current generation
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void exportIndividualData(Population pop, int gen)
			throws Exception {
		// Create file
		FileWriter fstream = new FileWriter("pop.txt", true);
		BufferedWriter out = new BufferedWriter(fstream);
		out.write("-------------------------------------------------------"
				+ sep);
		out.write("Generation " + gen + sep);
		for (int i = 0; i < pop.getNumberOfIndividuals(); i++) {
			Individual ind = pop.getIndividual(i);
			out.write("Individual " + i + sep);
			out.write("Position:" + sep);
			out.write(pop.getParentOptimization().getSearchSpace()
					.toString(ind.getPosition())+sep);
			out.write("Position Fitness: "+ind.getPositionFitness() + sep);
		}
		out.flush();
		// Close the output stream
		out.close();
	}

}
